import React, { useRef, useState, useEffect, useMemo, useImperativeHandle, forwardRef, useCallback } from 'react';
import { Table, Tabs, Search, Button, ActionText, PageHeader, history } from '@library';
import preDeletePrompt from '@library/components/button/preDeletePrompt';
import moment from 'moment';
import Axios from 'axios';
import { TabsRefProps } from '@library/components/tabs/Tabs';
import { __Sorter__ } from '@library/components/table/util';
import { ColumnsSetButton, useSetColumnsFun } from '../../../../components/customColumns/CustomColumnsButton';
import evalScriptText, { goToForm, ctx } from '../../eval';
import ModalForm from './_ModalForm';
import PageTable from './table/Table';
import ExportModal from './_ExportModal';
import { deleteByUrl } from './api';
import { parsingStr } from './util';
import QuerySession from '../../../../../src/components/querySession/_QuerySession';
import { DataListRef, DataListProps, ModalFormRef } from './interface';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { ShowModalOptionsType } from './../../interface';
import cls from './datalist.module.scss';

const emptyArr: any[] = [];
const T = window.$app.t;
const QuerySessionIns = new QuerySession();

type TabType = DataListProps & {
  id: string;
  label: string;
  [prop: string]: any;
};

type CurrOptionType = DataListProps & {
  pages?: any;
  fuzzyValue?: string;
  isSearch?: boolean;
  placeholder?: string;
  hideAddBtn?: boolean;
  showCount?: boolean;
  fuzzyField?: any[];
};

type ItemActionOptionType = {
  tabIndex: number;
  actionIndex: number;
  hide: boolean;
};

function handleTree(data: any[], id: string, parentId: string, children?: string) {
  id = id || 'id';
  parentId = parentId || 'parentId';
  children = children || 'children';
  //对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data));
  //循环所有项
  const treeData = cloneData.filter((father: any) => {
    let branchArr: any = cloneData.filter((child: any) => {
      //返回每一项的子级数组
      return father[id] === child[parentId];
    });
    branchArr.length > 0 && (father.children = branchArr);
    //返回第一层
    return father[parentId] === undefined || father[parentId] === null;
  });
  return treeData !== '' ? treeData : data;
}

function handleCustomQuery(query: string, allValues: any) {
  let customQuery = query?.includes('{{') ? parsingStr(query, {
    ...allValues,
    _USER_: ctx._USER_
  }) : query;

  if (typeof customQuery === 'string' && customQuery) customQuery = JSON.parse(customQuery);

  return customQuery ? { ...(customQuery as any) } : {};
}

const getDefaultOrder = () => {
  const cacheSorterObj = window[__Sorter__]?.[history.location.pathname];

  if (cacheSorterObj) {
    const column: any = Object.values(cacheSorterObj)[0];
    if (column?.field && column?.order) return [[column.field, column.order === 'ascend' ? 'ASC' : 'DESC']];
  }
}

export default forwardRef((props: DataListProps, ref: React.Ref<DataListRef>) => {
  const modalFormRef = useRef<ModalFormRef>(null);
  const exportExcelRef = useRef({ show: Function, hide: Function });
  const boxRef = useRef<HTMLDivElement>(null);
  const tableRef = useRef<any>(null);
  const tabsRef = useRef<any>([]);
  const isInit = useRef(false);
  const searchRef = useRef<any>(null);
  const isChangeTab = useRef(false);
  const [tabs, setTabs] = useState<TabType[]>([]);
  const [currTab, setCurrTab] = useState<TabType['id']>('');
  const [searchStr, setSearchStr] = useState('');
  const [reload, setReload] = useState(false);
  const [refreshTimer, setRefreshTimer] = useState(0);
  const [dataSource, setDataSource] = useState<any[]>();
  const [pages, setPages] = useState<any>(undefined);
  const [currOption, setCurrOption] = useState<CurrOptionType>({} as any);
  const [columnsNeeds, setColumnsNeeds] = useState<typeof props.columns>([]);
  const columnsList: any[] = useSetColumnsFun?.(columnsNeeds);
  const isManualRefresh = useRef(false);
  const isSearch = useRef(false);
  const tabsComponentRef = useRef<TabsRefProps>(null);
  const loadCountTimerRef = useRef<any>(null);
  const [itemActionOptions, setItemActionOption] = useState<ItemActionOptionType[]>([]);
  const [actionText, setActionText] = useState<string | { cn: string, en: string }>('');
  const cornermark = useRef<Record<string, number>>({});
  const [order, setOrder] = useState<Array<string[]>>(getDefaultOrder() || []);

  useQueryControlWrap(props.id, '', props.domComplete);

  useEffect(() => {
    // _REFRESH_DATALIST_ 主要为了处理shell切换界面
    // 如a切到b，切同时都包含datalist组件，dataList不会更新
    if (isInit.current && !props.isDesign && !(window as any)._REFRESH_DATALIST_) return;

    let tempTabs: any[] = [];

    if (props.tabsOption?.length) {
      tempTabs = props.tabsOption.map(item => {
        return {
          btnGroup: props.btnGroup,
          fuzzyField: item.fuzzyField || props.fuzzyField,
          label: localStorage.i18nextLng === 'en' ? item.labelEn : item.lable,
          _label: localStorage.i18nextLng === 'en' ? item.labelEn : item.lable,
          ...item
        };
      });
    }
    else {
      tempTabs.push({
        ...props,
        btnGroup: props.btnGroup,
        id: '',
        label: '',
        _label: '',
      });
    }

    isInit.current = true;

    setTimeout(() => {
      (window as any)._REFRESH_DATALIST_ = false;
    }, 100);

    if (loadCountTimerRef.current) {
      clearTimeout(loadCountTimerRef.current);
      loadCountTimerRef.current = null;
    }

    loadCountTimerRef.current = setTimeout(() => {
      loadCountTimerRef.current = null;

      props.validateFields?.(false, undefined, false).then((allValues: any) => {
        const allCountServers: Array<{ url: string, id: string, data: any; }> = [];

        for (const item of tempTabs) {
          if (item.showCount) {
            let customQuery = handleCustomQuery(item.query, allValues);
            const currInterceptors = props.getCurrInterceptors?.(item.url!);

            allCountServers.push({
              url: item.url.includes('bk/api') ? item.url.replace('/find', '/count') : item.url,
              data: currInterceptors?.set ? currInterceptors.set(customQuery, {}) : customQuery,
              id: item.id
            });
          }
        }

        Axios.all(
          allCountServers.map(item => {
            return Axios.post(item.url, item.data);
          })
        ).then(ress => {
          if (ress) {
            const obj = {};

            allCountServers.forEach((tab, index) => {
              const res = ress[index];

              if (res.status === 200 && res.data?.status === 200) {
                obj[tab.id] = res.data.result.count;
              }
            });
            cornermark.current = obj;
            tabsComponentRef.current?.setCornermark(obj);
          }
        }).catch(() => { });
      });
    }, 200);

    setTabs(tempTabs);
    tabsRef.current = tempTabs;
    setCurrTab(prev => prev ? prev : tempTabs[0].id);
  }, [props]);

  useEffect(() => {
    const curr = tabsRef.current.length === 1 ? tabsRef.current[0] : tabsRef.current.find((item: any) => item.id === currTab);

    if (curr) {
      let query: any = {};
      let str = T('pleaseEnter');

      if (pages) query.pages = pages;

      if (curr.fuzzyField && curr.fuzzyField.length) {
        query.fuzzyValue = isChangeTab.current ? '' : searchStr;
        query.fuzzyQuery = true;

        let tempFuzzyField: string[] = [],
          len = curr.fuzzyField.length;

        curr.fuzzyField.forEach((_item: any, index: number) => {
          const item = typeof _item === 'string' ?
            (curr.columns?.find((i: any) => i.dataIndex === _item) || {})
            : curr.columns?.find((i: any) => i.dataIndex === _item.value);

          if (item) {
            tempFuzzyField.push(item.dataIndex);
            item.label = (localStorage.i18nextLng === 'en' ? item?.titleEn : item?.title) || item?.title;
            str += (item?.label + (index === len - 1 ? '' : '/'));
          }
        });

        query.fuzzyField = tempFuzzyField;
        isChangeTab.current = false;
      }

      const columns = curr.columns || [];
      const actionBtnGroup = curr?.actionBtnGroup || [];
      const displayedAction = props.disabled ? curr.actionBtnGroup?.filter((item: any) => item.type !== 'edit') : curr?.actionBtnGroup;

      if (displayedAction.length && !props.isDesign && columns.every((item: any) => item.dataIndex !== 'action')) {
        columns.push({
          title: T('action'),
          dataIndex: 'action',
          fixed: 'right',
          width: actionBtnGroup.reduce((next: number, cur: any) => {
            let ml = actionBtnGroup.length === 1 ? 16 : (next ? 16 : 0);
            next = next + ml + (cur.text?.length || 4) * 18;
            return next;
          }, 0)
        })
      };

      if (props.validateFields) {
        props.validateFields?.(false, undefined, false).then((allValues: any) => {
          let customQuery = curr.query?.includes('{{') ? parsingStr(curr.query, {
            ...allValues,
            _USER_: ctx._USER_
          }) : curr.query;


          if (typeof customQuery === 'string' && customQuery) customQuery = JSON.parse(customQuery);

          const currInterceptors = props.getCurrInterceptors?.(curr.url!);
          const mergeQuery = { ...query, ...(customQuery as any), include: { all: true } };

          if (order.length) mergeQuery.order = order;

          const btnGroup = curr.btnGroup?.filter((item: any) => {
            return item.tabIds ? !item.tabIds.includes(curr.value) : true;
          });

          const interceptorsOptions = { type: '' };
          if (isSearch.current) interceptorsOptions.type = 'search';

          setCurrOption({
            ...curr,
            btnGroup,
            query: currInterceptors?.set ? currInterceptors.set(mergeQuery, interceptorsOptions) : mergeQuery,
            isSearch: !!curr.fuzzyField?.length,
            placeholder: str[str.length - 1] === '/' ? str.substring(0, str.length - 1) : str,
            columns
          });

          isSearch.current = false;

          if (props.autoLoad === false && isManualRefresh.current) {
            setTimeout(() => {
              tableRef.current?.onRefresh();
              isManualRefresh.current = false;
            }, 200);
          }
        });
      } else {
        setCurrOption({
          ...curr,
          isSearch: !!curr.fuzzyField?.length,
          placeholder: str[str.length - 1] === '/' ? str.substring(0, str.length - 1) : str,
          url: '' // url设置空 设计界面不需要请求方法
        });

        if (props.autoLoad === false && isManualRefresh.current) {
          setTimeout(() => {
            tableRef.current?.onRefresh();
            isManualRefresh.current = false;
          }, 200);
        }
      }
    }

    // eslint-disable-next-line
  }, [currTab, searchStr, refreshTimer, pages, reload, props.autoLoad, props.disabled, order]);

  useEffect(() => {
    if (history._isFromBreadcrumb || (sessionStorage._isFromBreadcrumb === 'true' || sessionStorage._isFromBreadcrumb === true)) {
      const queryObj = QuerySessionIns.getQuerySession();

      if (queryObj) {
        setCurrTab(queryObj.currTab);
        setSearchStr(queryObj.fuzzyValue);
        setPages(queryObj.pages);
      }
      history._isFromBreadcrumb = false;
    }
  }, []);

  useImperativeHandle(ref, () => ({
    getData(type?: 'view') {
      // 不将dataSource合并至_OBJ1_，showRowSelection为true时不处理兼容老的表单
      if (type === 'view' && !currOption.showRowSelection) return [];

      const fnName = currOption.showRowSelection || props.treeStructure ? 'getSelectedRows' : 'getDataSource';
      return tableRef.current?.[fnName]() || [];
    },
    setData(data: any) {
      if (data && Array.isArray(data)) {
        tableRef.current.setDataSource(data);
      }
    },
    getColumns() {
      return columnsList.map(item => ({ ...item, width: 20 }));
    },
    setCustomizedItemAction(options: Array<ItemActionOptionType>) {
      setItemActionOption(options);
    },
    onListRefresh(options: { refreshCurTabCornermark?: boolean; }) {
      isManualRefresh.current = true;
      tableRef.current?.setSelectRowKeys([]);
      setRefreshTimer(prev => prev + 1);
      modalFormRef?.current?.hide?.();

      if (options?.refreshCurTabCornermark) {
        const tab = tabs.find(tab => tab.id === currTab);
        if (!tab?.showCount) return;

        props.validateFields?.(false, undefined, false).then((allValues: any) => {
          let customQuery = handleCustomQuery(tab.query, allValues);
          const currInterceptors = props.getCurrInterceptors?.(tab.url!);

          Axios.post(
            (tab.url!.includes('bk/api') ? tab.url!.replace('/find', '/count') : tab.url) as string,
            currInterceptors?.set ? currInterceptors.set(customQuery, {}) : customQuery
          ).then(res => {
            if (res.status === 200 && res.data?.status === 200) {
              cornermark.current[tab.id] = res.data.result.count;
              tabsComponentRef.current?.setCornermark(cornermark.current);
            }
          }).catch(error => { });
        });
        return;
      }

      props.validateFields?.(false, undefined, false).then((allValues: any) => {
        const allCountServers: Array<{ url: string, id: string, data: any; }> = [];

        for (const item of tabs) {
          if (item.showCount) {
            let customQuery = handleCustomQuery(item.query, allValues);
            const currInterceptors = props.getCurrInterceptors?.(item.url!);

            allCountServers.push({
              url: item.url!.includes('bk/api') ? item.url!.replace('/find', '/count') : item.url!,
              data: currInterceptors?.set ? currInterceptors.set(customQuery, {}) : customQuery,
              id: item.id
            });
          }
        }

        Axios.all(
          allCountServers.map(item => {
            return Axios.post(item.url, item.data);
          })
        ).then(ress => {
          if (ress) {
            const obj = {};

            allCountServers.forEach((tab, index) => {
              const res = ress[index];

              if (res.status === 200 && res.data?.status === 200) {
                obj[tab.id] = res.data.result.count;
              }
            });

            cornermark.current = obj;
            tabsComponentRef.current?.setCornermark(obj);
          }
        }).catch(() => { });
      });
    },
    openExportDialog(v: any) {
      v.query = { ...v?.query, ...((currOption as any).query || {}) };
      exportExcelRef.current?.show?.(v);
    },
    setSearchValue(v: string) {
      setSearchStr(v);
    },
    hideTabs(tabsValue: string[]) {
      const filterTabs = tabs.filter(tab => !tabsValue.includes(tab.value));
      setTabs(filterTabs);
      if (filterTabs.length) {
        changeTab(filterTabs[0].id);
      }
    },
    setActionText(text: string | { cn: string; en: string }) {
      setActionText(text)
    }
  }));

  useEffect(() => {
    if (props.initialValue && Array.isArray(props.initialValue) && !props.url) {
      setDataSource(props.initialValue);
    }
  }, [props.initialValue, props.url]);

  const handColumns = useMemo(() => {
    const newColumns = columnsList.map(item => {
      if (item.dataIndex === 'action') {
        let title = T('action');
        if (actionText) {
          title = typeof actionText === 'string' ? actionText : (localStorage.i18nextLng === 'en' ? (actionText?.en || actionText?.cn) : actionText?.cn);
        }
        return { ...item, title }
      }
      // 转成table组件format
      if (item.moneyFormat) item.format = 'money';
      item.title = localStorage.i18nextLng === 'en' ? (item.titleEn || item.title) : item.title;
      item.tooltip = true;
      item.ellipsis = true;
      item.fixed = item.fixed || false;
      item.width = item.width || 100;
      item.sorterFn = item.serverSortFlag ? (order: string) => {
        if (order) setOrder([[item.dataIndex, order === 'ascend' ? 'ASC' : 'DESC']]);
        else setOrder([]);

        // 非自动获取数据，需要手动调用方法刷新
        if (props.autoLoad === false) {
          setTimeout(() => tableRef.current?.onRefresh(), 200)
        }
      } : undefined;

      return item;
    });

    return newColumns;
  }, [columnsList, actionText, props.autoLoad]);

  async function onEdit(record: object, url: string) {
    if (currOption.jumpNewPage) {
      goToForm(
        currOption.formName!,
        {
          url,
          ...record,
          showPageHeaderBtn: !!url,
          _sourceActionType: 'edit',
          _breadCrumbName: currOption.breadCrumbName
        });
      const query = tableRef.current?.getQuery!();
      QuerySessionIns.setQuerySession({ ...(currOption.query as any), currTab, pages: query.pages });
    } else {
      const values = await props.validateFields?.(false, undefined, false);
      const _record = {
        ...record,
        _sourceActionType: 'edit',
        _HEAD_: {
          ...values,
          _BUSINESS_: props.business
        }
      };

      modalFormRef?.current?.show?.(_record, currOption.formName!, url);
    }
  }

  function onDetail(record?: object) {
    if (currOption.jumpNewPage) {
      goToForm(
        currOption.formName!,
        {
          url: currOption.url,
          ...record,
          showPageHeaderBtn: false,
          disabled: true,
          _sourceActionType: 'detail',
          _breadCrumbName: currOption.breadCrumbName
        });
      const query = tableRef.current?.getQuery!();
      QuerySessionIns.setQuerySession({ ...(currOption.query as any), currTab, pages: query.pages });
    } else {
      modalFormRef?.current?.show?.(
        { ...record, _sourceActionType: 'detail' },
        currOption.formName!,
        '',
        true
      );
    }
  }

  const tableExtra = () => {
    const arr = [
      {
        dataIndex: 'action',
        render: (_: any, record: any) => {
          const tabIndex = tabs.findIndex(tab => tab.id === currTab);
          const actionBtnGroup = currOption.actionBtnGroup?.filter((btn, index) => {
            return !itemActionOptions.find(item => item.tabIndex === tabIndex && index === item.actionIndex)?.hide
              && !(btn.displayScript && eval(parsingStr(btn.displayScript, record)));
          });

          const showActionBtnGroup = actionBtnGroup?.filter((item: any) => {
            if ((item.type === 'edit' || item.type === 'detail') && currOption.formName) return true;
            if (item.type === 'delete' && !props.disabled) return true;
            if(item.type === 'others' && item.scriptText) return true;
            return false
          });

          return showActionBtnGroup?.map((item: any) => {
            let actionTextOption: any = null;

            if (item.type === 'edit' && currOption.formName) {
              actionTextOption = {
                type: item.text,
                onClick: () => onEdit(record, item.url!)
              };
            } else if (item.type === 'detail' && currOption.formName) {
              actionTextOption = {
                type: item.text,
                onClick: () => {
                  onDetail(record);
                }
              };
            } else if (item.type === 'delete' && !props.disabled) {
              actionTextOption = {
                type: item.text,
                onClick: () => {
                  preDeletePrompt(async () => {
                    const res = await deleteByUrl(item.url, record.id);
                    if (res) setRefreshTimer(prev => ++prev);
                  });
                }
              };
            } else if (item.type === 'others') {
              actionTextOption = {
                type: item.text,
                onClick: () => actionClick(item.scriptText!, record)
              };
            }

            return <ActionText {...actionTextOption}>{localStorage.i18nextLng === 'en' ? (item.textEn || item.text) : item.text}</ActionText>;
          });
        }
      }
    ];

    currOption.columns?.forEach((item: any) => {
      arr.push({
        dataIndex: item.dataIndex,
        render: (tx: any, record: any) => {
          // 处理关联form
          if (item.formName) {
            return (
              <ActionText.Detail
                type={item.text || undefined}
                onClick={() => {
                  modalFormRef.current?.show?.(
                    typeof tx === 'object' ? tx : {},
                    item.formName!,
                    '',
                    true
                  );
                }} />
            );
          }


          // 配置了转换文字
          if (item.statusTransferEn || item.statusTransfer) {
            const statusTransfer = localStorage.i18nextLng === 'en' ? item.statusTransferEn : item.statusTransfer;

            if (statusTransfer) {
              const obj = JSON.parse(statusTransfer);
              if (typeof tx === 'boolean') tx = tx ? 'true' : 'false';
              return obj[tx] || '';
            }
          }

          // 处理数组对象展示
          if (Array.isArray(tx) || Object.prototype.toString.call(tx) === '[object Object]') {
            tx = JSON.stringify(tx);
            return tx || '';
          }

          // 需要取子级字段
          if (item.dataIndex.includes('.')) {
            const arr = item.dataIndex.split('.');
            const dataIndex = arr.shift();

            return parsingStr(arr.join('.'), record[dataIndex]);
          }

          if (typeof tx === 'boolean') {
            return tx ? '是' : '否';
          }

          if (item.dateFormat && tx) {
            return moment(tx).format(item.dateFormat);
          }

          if (item.clickScript) {
            return (
              <span className='common-link' onClick={() => actionClick(item.clickScript, record)}>
                {tx}
              </span>
            );
          }

          return tx;
        }
      });
    });

    return arr;
  };

  async function showAddForm() {
    if (currOption.jumpNewPage) {
      return goToForm(currOption.formName!, {
        url: currOption.addUrl,
        showPageHeaderBtn: !!currOption.addUrl
      });
    }

    const values = await props.validateFields?.(false, undefined, false);

    modalFormRef?.current?.show?.({
      _HEAD_: { ...values, _BUSINESS_: props.business }
    },
      currOption.formName!,
      currOption.url!
    );
  }

  const dataSourceChange = useCallback((data) => {
    props.onValuesChange?.(`${props.name || props._id}`, data);
  }, [props.name, props._id]);

  function changeTab(tabid: string) {
    setPages(undefined);
    setCurrTab(tabid);
    searchRef.current?.resetKeyWords();
    setSearchStr('');
    isChangeTab.current = true;

    const tabsOption = props.tabsOption || [];
    const currOption = tabsOption.find(item => item.id === tabid);

    props.onValuesChange?.(`${props.name || props._id}#${currOption?.value || tabid}`, {});
  }

  function onTabClick(tabid: string) {
    if (tabid === currTab) {
      tableRef.current?.onRefresh();
    }
  }

  async function actionClick(scriptText: string, record?: any) {
    if (scriptText) {
      const values = await props.validateFields?.(false, undefined, false);
      if (record) values._record = record;
      const refsKey = Object.keys(props.controlRefs as any);
      const refDataList: any = [];

      if (refsKey.length) {
        for (let item of refsKey) {
          if (props.controlRefs?.[item]?.onListRefresh) {
            refDataList.push(props.controlRefs?.[item]);
          }
        }
      }

      evalScriptText({
        scriptText,
        extra: {
          _OBJ_: record,
          _OBJ1_: values,
          _ENV_: props?.enviromentConfig || {},
          _REFS_: refDataList,
          _QUERY_: currOption.query,
          showModal: (options: ShowModalOptionsType) => props.showModal?.(options, props._id + '_others'),
          parentNext: props.parentNext
        },
        next: () => { }
      });
    }
  }

  function handleResult(result: any) {
    const currInterceptors = props.getCurrInterceptors?.(currOption.url!);
    result = currInterceptors?.get ? currInterceptors.get(result) : result;

    if (props.treeStructure) {
      const row = Array.isArray(result) ? result : (result?.rows || []);
      let arr: any[] = [];
      row.forEach((element: any) => {
        arr.push(element);
        if (element.PurOrderLines) {
          arr = arr.concat(element.PurOrderLines);
        }
      });

      const _source = handleTree(arr, props.treeId!, props.treeParentId!);
      const _res = { rows: _source, count: _source.length, originArray: row };

      return _res;
    } else {
      return result;
    }
  }

  function handleExportQuery(query: any, options: { exportDataType: 'part' | 'all'; }) {
    // 部份导出
    if (options.exportDataType === 'part') {
      const rows = tableRef.current.getSelectedRows();

      return {
        ...query,
        where: {
          ...query.where,
          id: rows.map(({ id }: { id: string; }) => id)
        }
      };
    }

    return query;
  }

  function onRowStyleFn(record: any) {
    if (props.rowCustomizationScript) {
      try {
        eval(`window._dataList_ = ${props.rowCustomizationScript}`);
        return (window as any)._dataList_(record);
      } catch (error) { }
    }
  }

  const expandable = useMemo(() => ({ defaultExpandAllRows: props.isExpand }), [props.isExpand]);
  const btnSearchAlignLeft = !props.showTabs && props.isActionBtnAlignLeft;

  const BtnSearch = () => (
    <>
      {currOption.isSearch && (
        <Search
          ref={searchRef}
          value={searchStr}
          placeholder={currOption.placeholder}
          onSearch={e => {
            if (searchStr === e) {
              setReload(!reload);
            }
            setSearchStr(e);
            setPages((prev: any) => prev ? { ...prev, page: 1 } : undefined);
            isChangeTab.current = false;
            isManualRefresh.current = true;
            isSearch.current = true;
          }} />
      )}

      {!props.disabled && currOption.formName && !currOption.hideAddBtn && (
        <Button.Create className={cls.btnMl} onClick={showAddForm} />
      )}

      {!props.disabled && currOption.btnGroup && (
        currOption.btnGroup.map((item) => {
          const _style: React.CSSProperties = {};
          if (item.background) {
            _style.background = item.background;
            _style.borderColor = item.background;
          }
          if (item.color) _style.color = item.color;

          return (
            <Button
              {...item}
              className={cls.btnMl}
              onClick={() => actionClick(item.scriptText!)}
              style={_style}>
              {localStorage.i18nextLng === 'en' ? item?.textEn : item?.text}
            </Button>
          )
        })
      )}
    </>
  );

  return (
    <div {...props}
      ref={boxRef}
      className={!props.isDesign ? cls.datalist : cls.datalistDesign}
      style={{ height: props.autoHeight === false ? 'auto' : !props.isDesign ? 0 : 'auto' }} >
      <PageHeader
        title={
          btnSearchAlignLeft ? <BtnSearch /> : (
            tabs.length > 0 && (
              <Tabs
                ref={tabsComponentRef}
                mode='tabs'
                tabs={tabs}
                curTabId={currTab}
                onChange={changeTab}
                onTabClick={onTabClick}
              />
            )
          )
        }
        extra={
          <div className={cls.extra}>
            {!btnSearchAlignLeft && <BtnSearch />}
            <ColumnsSetButton
              columns={currOption.columns || emptyArr}
              onSendColumns={setColumnsNeeds}
              businessId={props._id + currTab} />
          </div>
        } />
      <div className='common-white-space'></div>
      {
        props.treeStructure ? <PageTable
          flat={props.isDesign}
          expandable={expandable}
          defaultRowSelection={{
            checkStrictly: !props.checkStrictly,
          }}
          rowSelectionType={currOption.showRowSelection ? 'checkbox' : undefined}
          dataSource={dataSource}
          ref={tableRef}
          recordSort={history.location.pathname}
          url={currOption.url}
          query={currOption.query as any}
          columns={handColumns}
          extra={tableExtra()}
          handleResult={handleResult}
        /> : <Table
          virtualListFlag
          dataSourceChange={dataSourceChange}
          autoLoad={typeof props.autoLoad === 'boolean' ? props.autoLoad : true}
          flat={props.isDesign}
          rowSelectionType={currOption.showRowSelection ? 'checkbox' : undefined}
          ref={tableRef}
          recordSort={history.location.pathname}
          url={currOption.url}
          query={currOption.query as any}
          columns={handColumns}
          extra={tableExtra()}
          handleResult={handleResult}
          onRowStyleFn={onRowStyleFn}
        />
      }

      <ModalForm
        formName={currOption.formName}
        ref={modalFormRef}
        callback={() => setRefreshTimer(prev => ++prev)} />

      <ExportModal
        query={currOption.query}
        handleQuery={handleExportQuery}
        ref={exportExcelRef} />
    </div>
  );
});